package com.itheima.reggie.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.JwtUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component // 登录拦截器
public class LoginCheckInterceptor implements HandlerInterceptor {

    // 权限拦截（鉴权）
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            // 1.取出请求头token
            String token = request.getHeader("Authorization");
            // 处理 Bearer （注意这里有空格）
            token = token.replace("Bearer ", "");
            // 2.解析token
            Map map = JwtUtil.parseToken(token);
            // 3. map to  user
            /*
                四个参数介绍
                    map – Map
                    beanClass – Bean Class
                    isToCamelCase – 是否将Map中的下划线风格key转换为驼峰风格
                    copyOptions – 转Bean选项
             */
            //将map集合解析成User对象
            User user = BeanUtil.mapToBean(map, User.class, true, CopyOptions.create());
            // 存入线程内
            UserHolder.set(user);

        } catch (Exception e) {
            e.printStackTrace();
            // 3.失败抛异常，返回NOTLOGIN
            ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");
            String json = JSON.toJSONString(resultInfo);
            response.getWriter().write(json);
            return false;
        }

        // 4.成功，放行
        return true;
    }


    // 返回之前，清理线程内user
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
